<script setup>
import {ref ,onMounted} from "vue";
import AddPP from "@/views/FM/C/components/AddPP.vue";
import EditePP from "@/views/FM/C/components/EditePP.vue";
import LookAPP from "@/views/FM/C/components/LookAPP.vue";
import { ElMessage } from 'element-plus';
import {get,del} from "@/http/http"


let fmList = ref([
]);
const pageNum = ref(1);
const pageSize = ref(10);
let total = ref(100);
let dialogFormVisible = ref(false);
//记录用户点击的按钮是添加还是编辑
let kind = ref("add");
//存储编辑按钮点击时对应的数据源
let data = ref(null);
let consultantName = ref("");
let title = ref("");
let disabled = ref(false);
//let role = ref("admin");
let roleInfo = ref({});
let selectedRows = ref([]);
let consultant = ref("");


onMounted(()=>{
  consultantName.value = JSON.parse(sessionStorage.getItem("consultant")).name;
  flush();
})

function flush(){
    roleInfo.value = JSON.parse(sessionStorage.getItem("consultant"));
    const res = get(`/lzs/FM/consultant/${roleInfo.value.id}`, {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    });
    res.then((res)=>{
      console.log(res);
      fmList.value = res.data.list;
      total.value = res.data.total;
    }).catch((err)=>{
      console.log(err);
    })
}

// function handleCurrentChange(val){
//   alert(val);
// }
// function handleSizeChange(val){
//   alert(val);
// }
function handleCurrentChange(){
  flush();
}
function handleSizeChange(){
  flush();
}

//定义事件绑定添加按钮
function addPP(){
  dialogFormVisible.value = true;
  kind.value = "add";
}
function editeAction(row){
  dialogFormVisible.value = true;
  kind.value = "edite";
  data.value = row;
}

function addFormData(form){
  fmList.value.push(form);
  dialogFormVisible.value = false;
  flush();
}

/*function selectByConsultantId(){
  const res = get("/lzs/FM", {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  });
  res.then((res)=>{
    console.log(res);
    fmList.value = res.data;
    total.value = res.total;
  }).catch((err)=>{
    console.log(err);
  })
}*/

function editeFormData(form){
  //查找需要更新的数据下标
  for(let i = 0; i < fmList.value.length; i++){
    if(fmList.value[i].id == form.id){
      //替换该数据
      fmList.value.splice(i, 1, form);
      break;
    }
  }
  dialogFormVisible.value = false;
  flush();
}

function search(){
  const res = get(`/lzs/FM/dynamic`, {
    title: title.value,
    consultantName: consultantName.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  });
  res.then((res)=>{
    console.log(res);
    fmList.value = res.data.list;
    total.value = res.data.total;
  }).catch((err)=>{
    console.log(err);
  })
}

function del1(row){
  //删除数据
  fmList.value = fmList.value.filter(item => item.id !== row.id);
  //发送请求
  del(`/lzs/FM/${row.id}`, {
    method: "DELETE"
  }).then((res)=>{
    console.log(res);
    ElMessage.success("删除成功");
  }).catch((err)=>{
    console.log(err);
    ElMessage.success("删除失败");
  })
}

function Look(row){
  dialogFormVisible.value = true;
  kind.value = "look";
  data.value = row;
}

function reset(){
  title.value = "";
  consultantName.value = "";
  flush();
}
function index(index){
  return (pageNum.value - 1) * pageSize.value + index + 1;
}

// 处理选中行变化
function handleSelectionChange(selection) {
  selectedRows.value = selection;
  console.log("选中的行：", selectedRows.value); // 调试输出
}

// 批量删除
function batchDelete() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的行");
    return;
  }

  const ids = selectedRows.value.map(row => row.id);
  del(`/lzs/FM`,
      {data: ids}
  ).then((res) => {
    console.log(res);
    ElMessage.success("批量删除成功");
    flush();
  }).catch((err) => {
    ElMessage.error("批量删除失败");
    console.log(err);
  });
}
</script>

<template>
  <div class="pp-page">
    <el-row>
      <el-col :span="4">
        <h3 class="pp-title">FM管理</h3>
      </el-col>
      <el-col :span="4" :offset="16" style="text-align: right;">
        <el-button type="primary" size="small" @click="addPP">添加</el-button>
      </el-col>
      <el-col :span="24" style="margin-top: 15px;border-top: 1px solid #f2f2f2; padding: 15px 0;">
        <el-row style="align-items: center;font-size: 14px;">
          <el-col :span="2" style="color: #999;padding-left: 10px;">标题：</el-col>
          <el-col :span="4">
            <el-input v-model="title"></el-input>
          </el-col>
          <el-col v-if="false" :span="2" style="color: #999; padding-left: 10px;">咨询师：</el-col>
          <el-col v-if="false" :span="4">
            <el-input v-model="consultant"></el-input>
          </el-col>
          <el-col :span="2" style="text-align: center">
            <el-button @click="search" type="primary" size="small">查询</el-button>
          </el-col>
          <el-col :span="2">
            <el-button @click="reset" type="default" size="small">重置</el-button>
          </el-col>
          <el-col :span="14" style="text-align: right">
            <el-button type="danger" @click="batchDelete" size="small">批量删除</el-button>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;">
          <el-col :span="24">
            <el-table :data="fmList" @selection-change="handleSelectionChange" style="width: 100%">
              <el-table-column
                  type="selection"
                  width="55"
              />
              <el-table-column
                  type="index"
                  label="编号"
                  width="60"
                  :index="index"
              />
              <el-table-column prop="title" label="标题" />
              <el-table-column prop="image" label="图片" >
                <template #default="scope">
                  <img :src="`http://localhost:8080/img?imgUrl=${scope.row.image}`"
                       alt="Image" style="width: 100px; height: 60px; object-fit: cover;"/>
                </template>
              </el-table-column>
              <el-table-column prop="intro" label="简介" >
                <template #default="scope">
                  <div class="ellipsis-text">{{ scope.row.intro }}</div>
                </template>
              </el-table-column>
              <el-table-column prop="consultantName" label="咨询师">
              </el-table-column>
              <el-table-column prop="publishTime" label="发布时间" />
              <el-table-column label="操作列表" width="200">
                <template #default="scope">
                  <el-button type="info"  @click="Look(scope.row)" size="small">查看</el-button>
                  <el-button type="warning" size="small" @click="editeAction(scope.row)">编辑</el-button>
                  <el-button type="danger" @click="del1(scope.row)" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24" style="display: flex;justify-content: flex-end;padding-top: 20px;">
            <el-pagination
                v-model:current-page="pageNum"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]"
                :size="size"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!--  设置对话框  -->
    <el-dialog v-model="dialogFormVisible" :title="kind === 'add' ? '添加FM' : dialogType === 'edit' ? '编辑FM' : '查看FM'" width="500">
      <AddPP v-if="kind == 'add'" @addValue="addFormData"></AddPP>
      <LookAPP v-else-if="kind == 'look'" :data="data" @close="dialogFormVisible = false"></LookAPP>
      <EditePP :data="data" @editeValue="editeFormData" v-else></EditePP>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.pp-page {
  background-color: #fff;
  padding: 20px;
  min-height: 100%;

  .pp-title {
    font-size: 16px;
    color: #555;
  }
  .normal {
    color: #409EFF;
  }
  .disable {
    color:#C0C4CC;
  }
}
.ellipsis-text {
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示两行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-word; /* 确保长单词也能换行 */
  line-height: 1.5; /* 设置合适的行高 */
  max-height: 3em; /* 两行文字的高度 (1.5 x 2) */
}
</style>